package com.fiume.travel.web;

import com.fiume.travel.enums.StatusEnum;
import com.fiume.travel.exception.ProjectException;
import com.fiume.travel.res.ResponseWrap;
import com.fiume.travel.service.UserService;
import com.fiume.travel.utils.EmptyUtil;
import com.fiume.travel.utils.ExceptionsUtil;
import com.fiume.travel.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * <p>
 * Description: 用户模块控制层
 * </p>
 *
 * @author fiume
 * @version v1.0.0
 * @create 2021-02-23 14:13
 * @see com.fiume.travel.web
 */
@RestController
@RequestMapping("/user")
@Log4j2
//用于跨域访问的
@CrossOrigin
@Api(tags = "用户模块")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private HttpSession session;

    /**
     * 用户注册
     * @param userVo 用户请求对象
     * @return 用户
     * @throws ProjectException 自定义异常
     */
    @PostMapping("/register")
    public ResponseWrap<Boolean> userRegisterController(@RequestBody UserVo userVo) throws ProjectException {
        Boolean result = userService.userRegister(userVo);
        // TODO: 在业务层判断直接返回对应的ResponseWrap,不用再捕获异常
            try {
                return ResponseWrap.<Boolean>builder()
                        .code(StatusEnum.SUCCEED.getCode())
                        .msg(StatusEnum.SUCCEED.getMsg())
                        .data(result)
                        .operationTime(new Date())
                        .build();
            }catch (Exception e){
                log.error("用户注册出错:{}", ExceptionsUtil.getStackTraceAsString(e));
                throw new ProjectException(StatusEnum.REGISTER_USER_FAIL.getCode(),StatusEnum.REGISTER_USER_FAIL.getMsg());
            }

    }

    /**
     * 用户登录
     * @param userVo 用户请求参数
     * @return 用户
     * @throws ProjectException 自定义异常
     */
    @PostMapping("/login")
    public ResponseWrap<UserVo> loginUser(@RequestBody UserVo userVo)
            throws ProjectException {
        try {
            UserVo resultUserVo = userService.userLogin(userVo);
            // 封装返回结果对象
            return ResponseWrap.<UserVo>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .data(resultUserVo)
                    .operationTime(new Date())
                    .build();
        } catch (Exception e) {
            // 将错误信息转成字符串,记录到错误的日志中
            log.error("用户登录：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.LOGIN_USER_FAIL.getCode(),
                    StatusEnum.LOGIN_USER_FAIL.getMsg());
        }
    }

    /**
     * 用户退出
     * @return 用户
     * @throws ProjectException 自定义异常处理
     */
    @GetMapping("/logout")
    public ResponseWrap<Boolean> loginOutUser() throws ProjectException {
        Boolean flag = true;
        try {
            // 调用service进行退出
            userService.userLoginOut();
            return ResponseWrap.<Boolean>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .operationTime(new Date())
                    .data(flag)
                    .build();
        }catch (Exception e){
            log.error("退出业务：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.FAIL.getCode(),
                    StatusEnum.FAIL.getMsg());
        }
    }

    /**
     * 用户是否登录
     * @return Boolean
     * @throws ProjectException 自定义异常
     */
    @GetMapping("/islogin")
    public ResponseWrap<Boolean> isLogin() throws ProjectException {
        try {
            Boolean result = userService.isLogin();
            return ResponseWrap.<Boolean>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .operationTime(new Date())
                    .data(result)
                    .build();
        }catch (Exception e){
            log.error("是否登录：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.ISLOGIN_FAIL.getCode(),
                    StatusEnum.ISLOGIN_FAIL.getMsg());
        }
    }

    /***
     *  获取当前用户信息
     * @return 用户
     */
    @GetMapping("/currentUser")
    public ResponseWrap<UserVo> currentUser() throws ProjectException {
        try {
            Object sessionAttribute = session.getAttribute(session.getId());
            if (!EmptyUtil.isNullOrEmpty(sessionAttribute)){
                return ResponseWrap.<UserVo>builder()
                        .code(StatusEnum.SUCCEED.getCode())
                        .msg(StatusEnum.SUCCEED.getMsg())
                        .operationTime(new Date())
                        .data((UserVo) sessionAttribute)
                        .build();
            }else {
                return ResponseWrap.<UserVo>builder()
                        .code(StatusEnum.SUCCEED.getCode())
                        .msg(StatusEnum.SUCCEED.getMsg())
                        .operationTime(new Date())
                        .data(null)
                        .build();
            }
        }catch (Exception e){
            //统一异常处理
            log.error("获取当前登录的用户信息：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.FAIL.getCode(),
                    StatusEnum.FAIL.getMsg());
        }
    }
}
